package com.rabbit.handler;

import org.slf4j.MDC;

import java.util.Map;

/**
 * <h1>装饰Runnable</h1>
 *
 * @author zjw
 * @date 2022/2/23 20:58
 */
public class MdcRunnable implements Runnable {

    private final Runnable runnable;

    /**
     * 保存当前主线程的MDC值
     */
    private final Map<String, String> mdcMap;

    public MdcRunnable(Runnable runnable) {
        this.runnable = runnable;
        this.mdcMap = MDC.getCopyOfContextMap();
    }

    @Override
    public void run() {
        for (Map.Entry<String, String> entry : mdcMap.entrySet()) {
            MDC.put(entry.getKey(), entry.getValue());
        }
        runnable.run();
        mdcMap.clear();
    }
}
